package com.pj.wisdomlogistics.ui.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.TakeawayInfo;
import com.pj.wisdomlogistics.entity.TakeoutMenuInfo;
import com.pj.wisdomlogistics.entity.WeekSsMenuInfo;
import com.pj.wisdomlogistics.mvp.contract.TakeoutMealContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.TakeoutMealPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.adapter.PopWeekMenuAdapter;
import com.pj.wisdomlogistics.ui.adapter.TakeOutDelicatessenAdapter;
import com.pj.wisdomlogistics.ui.adapter.TakeOutPastaAdapter;
import com.pj.wisdomlogistics.ui.view.CountDownView;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.Log;
import com.pj.wisdomlogistics.utils.NoDoubleClickUtils;
import com.pj.wisdomlogistics.utils.ScreenUtils;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.OnClick;


public class TakeoutMealActivity extends MvpActivity<TakeoutMealPresenter> implements TakeoutMealContract.View, TakeOutDelicatessenAdapter.countListener, TakeOutPastaAdapter.countListener {
    @BindView(R.id.rv_ss)
    RecyclerView mRvSs;
    @BindView(R.id.rv_ms)
    RecyclerView mRvMs;
    @BindView(R.id.tv_send)
    TextView mTvSend;
    @BindView(R.id.ll_Ss)
    LinearLayout mLlSs;
    @BindView(R.id.fl_layout)
    FrameLayout frameLayout;
    @BindView(R.id.countDownView)
    CountDownView countDownView;


    private TakeOutDelicatessenAdapter mSsAdapter;
    private TakeOutPastaAdapter mMsAdapter;
    private PopupWindow mPopWindow;
    private int place;

    private Map<Integer, TakeawayInfo> mDelicatessenMap;
    private Map<Integer, TakeawayInfo> mPastaMap;

    private long endTime = 12 * 60 * 60;


    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        ultimateBar.setColorBar(ContextCompat.getColor(this, R.color.text_blue));


        mDelicatessenMap = new HashMap<>();
        mPastaMap = new HashMap<>();
        place = getIntent().getIntExtra(Cons.TakeoutMeal.CHECKED_ST, -1);
//        if (place == 0) {
//            mLlSs.setVisibility(View.GONE);
//        } else {
            mRvSs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            mSsAdapter = new TakeOutDelicatessenAdapter(this);
            mRvSs.setAdapter(mSsAdapter);
            mSsAdapter.setListener(this);
      //  }

        mRvMs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mMsAdapter = new TakeOutPastaAdapter(this);
        mRvMs.setAdapter(mMsAdapter);
        mMsAdapter.setListener(this);

        mPresenter.getTimestamp();
        mPresenter.findOutFoodList(place);
        showProgressDialog();
    }


    @OnClick({R.id.iv_back, R.id.iv_ss_detail, R.id.tv_send, R.id.iv_ms_detail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.iv_ms_detail:
//                ScaleMoveImageViewer mImageView = new ScaleMoveImageViewer(this);
//                mImageView.setImageResource(R.drawable.menu_ms);
//
//                AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                AlertDialog ad = builder.create();
//                ad.setCanceledOnTouchOutside(true);
//                ad.setView(mImageView);
//                ad.show();
                Intent intent1 = new Intent(this , TakeOutH5Activity.class);
                intent1.putExtra("place" , place);
                intent1.putExtra("type" , 0);
                startActivity(intent1);
                break;
            case R.id.iv_ss_detail:
                //mPresenter.findCookFoodList();
                Intent intent2 = new Intent(this , TakeOutH5Activity.class);
                intent2.putExtra("place" , place);
                intent2.putExtra("type" , 1);
                startActivity(intent2);
                break;
            case R.id.tv_send:
                if(NoDoubleClickUtils.isDoubleClick()) return;

                if (mDelicatessenMap.size() == 0 && mPastaMap.size() == 0) {
                    CustomToast.showToast(this, "请选择您要订购的菜品", 1000);
                    return;
                }

                String mDelicatessen = "";
                if (mDelicatessenMap.size() != 0) {
                    for (TakeawayInfo mInfo : mDelicatessenMap.values()) {
                        mDelicatessen +=
                                mInfo.getFoodId() + ","
                                        + mInfo.getFoodName() + ","
                                        + mInfo.getTotalPrice() + ","
                                        + mInfo.getCount() + ","
                                        + mInfo.getUnit() + ";";
                    }
                    mDelicatessen = mDelicatessen.substring(0, mDelicatessen.length() - 1);
                }

                String mPasta = "";
                if (mPastaMap.size() != 0) {
                    for (TakeawayInfo mInfo : mPastaMap.values()) {
                        if (mInfo.getCount() == 0) continue;
                        mPasta +=
                                mInfo.getFoodId() + ","
                                        + mInfo.getFoodName() + ","
                                        + mInfo.getTotalPrice() + ","
                                        + mInfo.getCount() + ","
                                        + mInfo.getUnit() + ";";
                    }
                    mPasta = mPasta.substring(0, mPasta.length() - 1);
                }

                Log.e("Tag", mDelicatessen);
                Log.e("Tag", mPasta);
                Log.e("Tag" , MyApplication.userID);
                Log.e("Tag" , place + "");
                mPresenter.submitFoodApply(mDelicatessen, mPasta, MyApplication.userID, place);
                showProgressDialog();
                break;

        }
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_takeout_meal;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }


    public void showPop(List<WeekSsMenuInfo> mList) {
        int screenWidth = ScreenUtils.getScreenWidth(this);
        int screenHeight = ScreenUtils.getScreenHeight(this);

        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_ss_of_week, null);
        mPopWindow = new PopupWindow(contentView,
                (int) (screenWidth * 0.8), RelativeLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setTouchable(true);
        mPopWindow.setBackgroundDrawable(new ColorDrawable());
        backgroundAlpha(0.3f);
        RecyclerView mRvSs = (RecyclerView) contentView.findViewById(R.id.rv_ss);
        mRvSs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        PopWeekMenuAdapter mAdapter = new PopWeekMenuAdapter(this);
        mRvSs.setAdapter(mAdapter);
        mAdapter.setList(mList);
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });

        mPopWindow.showAtLocation(mTvSend, Gravity.NO_GRAVITY, (int) (screenWidth * 0.2 / 2), (int) (screenHeight * 0.2));
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        this.getWindow().setAttributes(lp);
    }

    @Override
    public void showError(String errorMsg) {
        dismissProgressDialog();
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showMenuSuccess(TakeoutMenuInfo mMenuInfo) {
        dismissProgressDialog();
        mMsAdapter.setData(mMenuInfo.getMianshi());
       // if (place == 1) {
            mSsAdapter.setData(mMenuInfo.getShushi());
       // }
    }

    @Override
    public void showWeekMenuSuccess(List<WeekSsMenuInfo> mWeekSsMenuInfos) {
        dismissProgressDialog();
        //showPop(mWeekSsMenuInfos);
        Intent mIntent = new Intent(this , WeekMenuActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("week_menu" , (Serializable) mWeekSsMenuInfos);
        mIntent.putExtras(bundle);
        mIntent.putExtra("type" , 1);
        startActivity(mIntent);
    }

    @Override
    public void showSendSuccess() {
        dismissProgressDialog();
        CustomToast.showToast(this, "提交成功", 1000);
        ActivityManagerUtil.create().finishActivity();
    }

    @Override
    public void getTimeSuccess(String time) {
        initTimeView(time);
    }

    private void initTimeView(String time){
        if(endTime <= getMs(Long.parseLong(time))){
            frameLayout.setVisibility(View.GONE);
        }else{
            frameLayout.setVisibility(View.VISIBLE);
            countDownView.initTime(endTime - getMs(Long.parseLong(time)));
            countDownView.start();
            countDownView.setOnTimeCompleteListener(new CountDownView.OnTimeCompleteListener() {
                @Override
                public void onTimeComplete() {
                    //计时完成
                    frameLayout.setVisibility(View.GONE);
                }
            });
        }
    }

    private long getMs(long ms){
        SimpleDateFormat formatter =
                new SimpleDateFormat("HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        String[] hms = formatter.format(ms).split(":");
        int h = Integer.parseInt(hms[0]);
        int m = Integer.parseInt(hms[1]);
        int s = Integer.parseInt(hms[2]);
        return h * 60 * 60 + m * 60 + s;
    }

    @Override
    public void itemClick(int id, int currentCount, String name, double price, String unit, int type) {
        switch (type) {
            case Cons.TakeoutMeal.DELICATESSEN:
                //熟食
                if (mDelicatessenMap.get(id) == null) {
                    TakeawayInfo mInfo = new TakeawayInfo();
                    mInfo.setFoodId(id);
                    mInfo.setFoodName(name);
                    mInfo.setTotalPrice(price * currentCount);
                    mInfo.setCount(currentCount);
                    mInfo.setUnit(unit);
                    mDelicatessenMap.put(id, mInfo);
                } else {
                    if (currentCount == 0) {
                        mDelicatessenMap.remove(id);
                    } else {
                        mDelicatessenMap.get(id).setCount(currentCount);
                        mDelicatessenMap.get(id).setTotalPrice(price * currentCount);
                    }
                }
                break;
            case Cons.TakeoutMeal.PASTA:
                //面食
                if (mPastaMap.get(id) == null) {
                    TakeawayInfo mInfo = new TakeawayInfo();
                    mInfo.setFoodId(id);
                    mInfo.setFoodName(name);
                    mInfo.setTotalPrice(price * currentCount);
                    mInfo.setCount(currentCount);
                    mInfo.setUnit(unit);
                    mPastaMap.put(id, mInfo);
                } else {
                    if (currentCount == 0) {
                        mPastaMap.remove(id);
                    }else{
                        mPastaMap.get(id).setCount(currentCount);
                        mPastaMap.get(id).setTotalPrice(price * currentCount);
                    }
                }
                break;
        }


    }

}
